<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      row-key="id"
      :data="list"
      border
      highlight-current-row
      style="width: 100%;"
      height="550"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="菜单名称" prop="name" align="left" width="280" />
      <el-table-column label="菜单路由" prop="route" align="center" width="150" />
      <el-table-column label="排序" prop="sort_id" align="center" width="150" />

      <el-table-column label="菜单描述" prop="description" width="420" align="center" />

      <el-table-column label="操作" fixed="right" align="center" min-width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建 -->
    <el-dialog class="data-form-dialog" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px">
        <el-form-item
          label="菜单名称"
          prop="name"
          :rules="[
            { required: true, message: '请填写菜单名称'},
            { type: 'string', message: '菜单名称必需是字符串'},
            { min: 2, max: 32, message: '长度2-32'}
          ]"
        >
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item
          label="菜单路由"
          prop="route"
          :rules="[
            { required: true, message: '请填写菜单路由'},
            { type: 'string', message: '菜单路由必需是字符串'},
            { min: 2, max: 32, message: '长度2-32'}
          ]"
        >
          <el-input v-model="temp.route" />
        </el-form-item>
        <el-form-item
          v-if="list.length"
          label="上级菜单"
          prop="label"
        >
          <el-cascader
            v-model="temp.parent_id"
            :options="parentData"
            :filter-method="searchParentNode"
            :props="{checkStrictly: true, expandTrigger: 'hover', value: 'id', label: 'name' }"
            @change="handleChangeParentMenu"
          />
        </el-form-item>
        <el-form-item
          label="排序(越大越前)"
          prop="sort_id"
          :rules="[
            { required: false, message: ''}
          ]"
        >
          <el-input v-model="temp.sort_id" />
        </el-form-item>
        <el-form-item
          label="菜单描述"
          prop="description"
          :rules="[
            { min: 0, max: 128, message: '长度2-128'}
          ]"
        >
          <el-input v-model="temp.description" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" :loading="submitLoading" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  fetchMenuList,
  fetchCreateMenu,
  fetchUpdateMenu
} from '@/api/menu'

export default {
  name: 'Menu',
  components: {},
  data() {
    return {
      tableKey: 0,
      list: [],
      menuData: {},
      total: 0,
      dialogFormVisible: false,
      dialogStatus: '',
      listLoading: true,
      submitLoading: false, // 提交中
      listQuery: {},
      temp: {
        id: 0,
        name: '',
        route: '',
        parent_id: [0],
        sort_id: 0,
        description: ''
      },
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {},
      parentData: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 可选上级菜单
    getParentList(id) {
      this.parentData = Object.assign([], this.list)
      this.disableSelfNode(id, this.parentData)
    },
    // 禁止自己
    disableSelfNode(id, data) {
      for (const i in data) {
        if (data[i].id === id) {
          data[i].disabled = true
          if (data[i].children.length > 0) {
            this.disableNode(data[i].children)
          }
          return true
        } else if (data[i].children.length > 0) {
          this.disableSelfNode(id, data[i].children)
        }
      }
      return
    },
    // 禁止
    disableNode(data) {
      for (const i in data) {
        data[i].disabled = true
        if (data[i].children.length > 0) {
          this.disableNode(data[i].children)
        }
      }
      return
    },

    // 搜索上级菜单
    searchParentNode(e, k) {
      if (e.name === k) return true
      return false
    },
    handleChangeParentMenu(e) {

    },
    resetTemp() {
      this.temp = {
        id: 0,
        name: '',
        route: '',
        sort_id: 0,
        parent_id: [0],
        description: ''
      }
    },
    // 创建
    handleCreate() {
      if (this.dialogStatus === 'update') {
        this.resetTemp()
      }
      this.dialogStatus = 'create'
      this.dialogFormVisible = true

      this.parentData = Object.assign([], this.list)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑
    handleUpdate(row) {
      const data = Object.assign({}, row) // copy obj
      this.temp.id = data.id
      this.temp.name = data.name
      this.temp.route = data.route
      this.temp.sort_id = data.sort_id
      this.temp.parent_id = [data.parent_id]
      this.temp.description = data.description
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.getParentList(this.temp.id)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 提交表单
    createData() {
      this.submitLoading = true
      this.submitData()
    },
    updateData() {
      this.submitLoading = true
      this.submintUpdateData()
    },
    submintUpdateData() {
      const _this = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          fetchUpdateMenu(_this.temp).then(() => {
            _this.getList()
            _this.dialogFormVisible = false
            _this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            _this.submitLoading = false
          }, () => {
            _this.submitLoading = false
          })
        } else {
          _this.submitLoading = false
        }
      })
    },
    submitData() {
      const _this = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          fetchCreateMenu(_this.temp).then((res) => {
            _this.getList()
            _this.dialogFormVisible = false
            _this.resetTemp()
            _this.$notify({
              title: 'Success',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })

            _this.submitLoading = false
          })
        } else {
          _this.submitLoading = false
        }
      })
    },
    getList() {
      fetchMenuList().then(res => {
        this.listLoading = false
        this.list = res.data.items
      }, rej => {
        this.listLoading = false
      })
    },
    jump(url) {
      this.$router.push(url)
    }
  }
}
</script>

<style>
  .el-dialog {
    width: 550px;
  }

  .cate-icon {
    width: 2.5rem;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .filter-container .filter-item {
    display: inline-block;
    vertical-align: middle;
  }
</style>
